package vip.liux.backend.application.serviceImpl.point;


import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.liux.application.dots.ListResultDto;
import vip.liux.backend.application.service.point.AutoMapperProfile;
import vip.liux.backend.application.service.point.PointsRuleDto;
import vip.liux.backend.application.service.point.PointsRuleService;
import vip.liux.contracts.models.point.PointsRule;
import vip.liux.contracts.repositories.point.IPointsRuleRepository;
import vip.liux.contracts.shared.enums.Status;

@Service
public class PointsRuleAdminServiceImpl implements PointsRuleService {

    @Autowired
    private IPointsRuleRepository pointsRuleRepository;

    @Override
    @Transactional
    public PointsRuleDto createRule(PointsRuleCreateDto dto) {
        PointsRule rule = pointsRuleRepository.save(AutoMapperProfile.INSTANCE.toEntity(dto));
        return AutoMapperProfile.INSTANCE.toDto(rule);
    }

    @Override
    @Transactional
    public PointsRuleDto updateRule(Long id, PointsRuleCreateDto dto) {
        PointsRule existingRule = pointsRuleRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("规则不存在"));
        AutoMapperProfile.INSTANCE.toEntity(dto, existingRule);
        existingRule = pointsRuleRepository.save(existingRule);
        return AutoMapperProfile.INSTANCE.toDto(existingRule);
    }

    @Override
    @Transactional
    public void toggleRuleStatus(Long ruleId, Status status) {
        PointsRule rule = pointsRuleRepository.findById(ruleId)
                .orElseThrow(() -> new IllegalArgumentException("规则不存在"));
        rule.setStatus(status);
        pointsRuleRepository.save(rule);
    }

    @Override
    public PointsRuleDto detailRule(String ruleCode) {
        PointsRule rule = pointsRuleRepository.findByRuleCode(ruleCode)
                .orElseThrow(() -> new IllegalArgumentException("规则不存在"));
        return AutoMapperProfile.INSTANCE.toDto(rule);
    }

    @Override
    public ListResultDto<PointsRuleDto> list() {
        return new ListResultDto<>(
                AutoMapperProfile.INSTANCE.toRuleDtos(pointsRuleRepository.findAll())
        );
    }
}